package cn.yywd_123.Light.main.utils;

/*
 *  Author: yywd_123
 *  Date: 2022/8/17d
 */

import cn.yywd_123.Light.AgentMain;
import cn.yywd_123.Light.main.LightMain;
import cn.yywd_123.Light.main.utils.codeMap.MapIndex;
import cn.yywd_123.Light.main.utils.codeMap.CodeMap;
import cn.yywd_123.Light.main.utils.codeMap.TransformField;
import cn.yywd_123.Light.main.utils.codeMap.TransformMethod;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class CodeParser {
	public CodeMap codeMap;

	public CodeParser(String gameVersion) {
		codeMap = getCodeMap(gameVersion);
		LightMain.logger.info("[Light] 正在使用版本" + AgentMain.getArg() + "的代码表");
	}

	public TransformMethod getTransformMethod(String targetName) {
		for (TransformMethod method : codeMap.getTransformMethods()) {
			if (method.getTransformTarget().equalsIgnoreCase(targetName)) return method;
		}
		return null;
	}

	public TransformField getTransformField(String targetName) {
		for (TransformField field : codeMap.getTransformFields()) {
			if (field.getTransformTarget().equalsIgnoreCase(targetName)) return field;
		}
		return null;
	}

	public CodeMap getCodeMap(String gameVersion) {
		try {
			BufferedReader mapIndex = new BufferedReader(new InputStreamReader(Objects.requireNonNull(LightMain.class.getClassLoader().getResourceAsStream("codeMaps/mapIndex.json")), StandardCharsets.UTF_8));
			StringBuilder sb = new StringBuilder();

			String buf;
			while ((buf = mapIndex.readLine()) != null) sb.append(buf);

			Gson gson = new Gson();
			MapIndex indexes = gson.fromJson(sb.toString(), MapIndex.class);

			BufferedReader map = new BufferedReader(new InputStreamReader(Objects.requireNonNull(LightMain.class.getClassLoader().getResourceAsStream(indexes.getVersionInfo(gameVersion).getMapPath())), StandardCharsets.UTF_8));

			StringBuilder sb1 = new StringBuilder();

			while ((buf = map.readLine()) != null) sb1.append(buf);

			return gson.fromJson(sb1.toString(), CodeMap.class);
		} catch (Exception e) {
			LightMain.logger.error("[Light] 找不到代码表,请在javaagent参数位置填写正确的客户端版本");
			e.printStackTrace();
			System.exit(-1);
		}
		System.exit(-1);
		return null;
	}
}
